﻿using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Web.Configuration;

namespace AddressBookDev.Utilities
{
    public static class Images
    {
        public static Image ResizeImage(Image image, Size size, bool preserveAspectRatio = true)
        {
            int newWidth;
            int newHeight;
            if (preserveAspectRatio)
            {
                int originalWidth = image.Width;
                int originalHeight = image.Height;
                float percentWidth = (float) size.Width/(float) originalWidth;
                float percentHeight = (float) size.Height/(float) originalHeight;
                float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
                newWidth = (int) (originalWidth*percent);
                newHeight = (int) (originalHeight*percent);
            }
            else
            {
                newWidth = size.Width;
                newHeight = size.Height;
            }
            Image newImage = new Bitmap(newWidth, newHeight);
            using (Graphics graphicsHandle = Graphics.FromImage(newImage))
            {
                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            return newImage;
        }

        public static Size GetContactImageSize()
        {
            return new Size(int.Parse(WebConfigurationManager.AppSettings["ContactImageWidth"]),
                int.Parse(WebConfigurationManager.AppSettings["ContactImageHeight"]));
        }

        public static string CreateImageUrl(params string[] urlParts)
        {
            string basePath = "/Content";
            foreach (string part in urlParts)
            {
                basePath += "/" + part;
            }
            return basePath;
        }

        public static Image CropBitmap(Image image,
                         int cropX, int cropY,
                         int cropWidth, int cropHeight)
        {
            Bitmap bitmap = new Bitmap(image);
            Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
            Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
            return cropped;
        }

        public static void DeleteContactImage(string contactFolder, int contactId)
        {
            Directory.Delete(contactFolder, true);
        }
    }
}